package com.shenmazong.serverwebpoem.controller;

import com.alibaba.fastjson.JSON;
import com.shenmazong.serverwebpoem.pojo.TbPoetry;
import com.shenmazong.serverwebpoem.service.ElasticSearchService;
import com.shenmazong.serverwebpoem.service.TbPoetryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 田不平
 * @project server-web-poem
 * @date 2020/3/26 5:32 PM
 * http://www.shenmazong.com
 */

@Slf4j
@Controller
public class ElasticSearchController {

    @Autowired
    RestHighLevelClient highLevelClient;

    @Autowired
    TbPoetryService tbPoetryService;

    @Autowired
    ElasticSearchService elasticService;

    @GetMapping(value = "/search")
    @ResponseBody
    public String search() {

        elasticService.createIndex();
        return "OK";
    }

    @RequestMapping(value = "/findText")
    @ResponseBody
    public Object findText(String keyWord) {
        return elasticService.findText(keyWord);
    }

    /**
     * TODO 根据关键字进行搜索
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/findByWord")
    public String findByWord(HttpServletRequest request, Model model) {

        String strPageNo = request.getParameter("pageNo");
        if(strPageNo == null) strPageNo = "1";
        String keyWord = request.getParameter("keyWord");
        Integer pageNo = Integer.parseInt(strPageNo);

        // 转换查询字符串编码
        try {
            keyWord = java.net.URLDecoder.decode(keyWord,"utf-8");
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        // 设置查询的页数
        Pageable pageable = PageRequest.of(pageNo-1,5);
        Page<TbPoetry> pageData = elasticService.findByWord(keyWord, pageable);

        List<TbPoetry> poetries = pageData.getContent();

        model.addAttribute("poetries", poetries);
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", pageData.getTotalPages());
        model.addAttribute("count", pageData.getTotalElements());

        try {
            keyWord = java.net.URLEncoder.encode(keyWord,"utf-8");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("keyWord", keyWord);

        // pageData.getTotalPages()
        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>pageData.getTotalPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>pageData.getTotalPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        return "find";
    }

//    public String createIndex() {
//        try {
//
//            // 1. 初始化
//            RestHighLevelClient client = new RestHighLevelClient(
//                    RestClient.builder(new HttpHost("localhost", 9200, "http")));
//
//            // 2. 创建索引
//            String indexName = "tb_poetry";
//            IndexRequest indexRequest = new IndexRequest(indexName);
//
//            TbPoetry poetry = tbPoetryService.getPoetryById(1);
//            String strPoetry = JSON.toJSONString(poetry);
//            indexRequest.source(strPoetry, XContentType.JSON);
//
//            // 3. 条件设置
//            indexRequest.routing("routing");
//            indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
//            indexRequest.setRefreshPolicy("wait_for");
//
//            // 4. 监听
//            IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
//            ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
//                @Override
//                public void onResponse(IndexResponse indexResponse) {
//                    log.info("indexResponse succeed!");
//                }
//
//                @Override
//                public void onFailure(Exception e) {
//                    log.info("indexResponse failed!");
//                }
//            };
//            client.close();
//        }
//        catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return "ok";
//    }
}
